import 'dart:math';

import 'package:aqua_plunge/constants/constants.dart';
import 'package:aqua_plunge/http/app_manager.dart';
import 'package:aqua_plunge/page/tab_navigation_page.dart';
import 'package:aqua_plunge/services/database_service.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../constants/colors.dart';
import '../cover/LogPvManager.dart';
import '../dao/broadcaster_dao.dart';
import '../dao/login_dao.dart';
import '../dao/media_dao.dart';
import '../model/Author.dart';
import '../model/Creation.dart';
import '../model/media.dart';
import '../util/view_util.dart';

///启动页，包含登录界面
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isChecked = false;
  bool loading = false;
  late LoginType _loginType;

  get _fasLoginView => GestureDetector(
        onTap: () {
          _loginType = LoginType.fastLogin;
          if (isChecked == false) {
            _DialogShow;
          } else {
            _login(_loginType);
          }
        },
        child: Align(
          alignment: Alignment.center, // 水平居中
          child: Container(
            width: 265,
            height: 55,
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage("images/icon_btn_fast_login.png"),
                fit: BoxFit.cover, // 图片适应容器，同时保持宽高比
              ),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  "images/icon_light.png",
                  width: 24,
                  height: 24,
                ),
                hiSpace(width: 8),
                const Text(
                  "Fast Login",
                  style: TextStyle(
                    color: Color(0xff4A46D4),
                    fontSize: 18,
                    decoration: TextDecoration.none,
                  ),
                )
              ],
            ),
          ),
        ),
      );

  get _signinApple => GestureDetector(
        onTap: () {
          _loginType = LoginType.appleLogin;
          if (isChecked == false) {
            _DialogShow;
          } else {
            _login(_loginType);
          }
        },
        child: Align(
          alignment: Alignment.center, // 水平居中
          child: Container(
            width: 265,
            height: 55,
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage("images/icon_btn_signin_with_apple.png"),
                fit: BoxFit.cover, // 图片适应容器，同时保持宽高比
              ),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  "images/icon_apple.png",
                  width: 24,
                  height: 24,
                ),
                hiSpace(width: 8),
                const Text(
                  "Sign in with Apple",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    decoration: TextDecoration.none,
                  ),
                )
              ],
            ),
          ),
        ),
      );

  get _checkbox => GestureDetector(
      onTap: () {
        setState(() {
          isChecked = !isChecked;
        });
      },
      child: isChecked
          ? Image.asset(
              "images/icon_checked.png",
              width: 12,
              height: 12,
            )
          : Image.asset(
              "images/icon_uncheck.png",
              width: 12,
              height: 12,
            ));

  get _privacyText => LimitedBox(
        maxWidth: 230,
        child: RichText(
          text: TextSpan(children: [
            const TextSpan(
                text: "By using our App you agree with our ",
                style: TextStyle(color: Colors.white, fontSize: 12)),
            TextSpan(
                text: "Term of Use",
                style: const TextStyle(color: Color(0xFF43D6C2), fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    jumpH5(url: Constants.termConditions, title: 'Term of Use');
                    LogPvManager.stat(page: Constants.pageTerms);
                  }),
            const TextSpan(
                text: "and",
                style: TextStyle(color: Colors.white, fontSize: 12)),
            TextSpan(
                text: "Privacy Policy",
                style: const TextStyle(color: Color(0xFF43D6C2), fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    jumpH5(url: Constants.privacy, title: 'Privacy Policy');
                    LogPvManager.stat(page: Constants.pagePrivacy);
                  }),
          ]),
        ),
      );

  get _DialogShow => showDialog(
        context: context,
        builder: (context) {
          return Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.0),
            ), // 设置圆角
            elevation: 0, // 阴影效果
            backgroundColor: Colors.transparent, // 背景颜色透明
            child: Container(
              // 使用Container包裹内容
              padding: EdgeInsets.fromLTRB(35, 10, 35, 20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.0), // 再次设置圆角
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min, // 使内容最小化
                children: <Widget>[
                  Image.asset(
                    "images/icon_app_logo.png",
                    width: 80,
                    height: 80,
                  ),
                  const SizedBox(height: 4),
                  const Text('AquaPlunge',
                      style: TextStyle(
                          color: AppColors.primaryColor,
                          fontSize: 14,
                          fontWeight: FontWeight.w900)),
                  const SizedBox(height: 10), // 垂直间距
                  const LimitedBox(
                      maxWidth: 204,
                      child: Text(
                        "By using our App you agree with our Term of Use and Privacy Policy.",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 12,
                            color: Color(0xff333333),
                            height: 1.5),
                      )),
                  const SizedBox(height: 20),
                  _agreeBtn,
                  const SizedBox(height: 12),
                  _cancelBtn
                  // _cancelBtn
                ],
              ),
            ),
          );
        },
      );

  get _agreeBtn => GestureDetector(
        onTap: () {
          setState(() {
            isChecked = true;
          });
          _login(_loginType);
          Get.back();
        },
        child: Container(
            width: 180,
            height: 36,
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage("images/icon_btn_signin_with_apple.png"),
                fit: BoxFit.cover, // 图片适应容器，同时保持宽高比
              ),
              borderRadius: BorderRadius.circular(15),
            ),
            child: const Center(
              child: Text(
                "Agree and Continue",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  decoration: TextDecoration.none,
                ),
              ),
            )),
      );

  get _cancelBtn => GestureDetector(
        onTap: () {
          Get.back();
        },
        child: Container(
          width: 180,
          height: 36,
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage("images/icon_cancel_btn.png"),
              fit: BoxFit.cover, // 图片适应容器，同时保持宽高比
            ),
            borderRadius: BorderRadius.circular(15),
          ),
        ),
      );

  _bottomContent() {
    return Container(
      padding: const EdgeInsets.only(left: 58, right: 58),
      child: Row(
        children: [_checkbox, hiSpace(width: 10), _privacyText],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(child: Image.asset("images/img_login_bg.png")),
        _content(),
        Visibility(
            visible: loading,
            child: const Center(
              child: CircularProgressIndicator(),
            ))
      ],
    );
  }

  _content() {
    return Container(
      padding: const EdgeInsets.only(top: 185),
      alignment: Alignment.center,
      child: Column(
        children: [
          Image.asset(
            "images/icon_app_logo.png",
            width: 120,
            height: 120,
          ),
          hiSpace(height: 24),
          const Text(
            "AquaPlunge",
            style: TextStyle(
                color: Colors.white,
                fontSize: 24,
                decoration: TextDecoration.none),
          ),
          hiSpace(height: 100),
          _fasLoginView,
          hiSpace(height: 16),
          _signinApple,
          hiSpace(height: 162),
          _bottomContent()
        ],
      ),
    );
  }

  void _appleLogin() async {
    LogPvManager.stat(page: Constants.pageAppleLogin);
    final credential = await SignInWithApple.getAppleIDCredential(scopes: [
      AppleIDAuthorizationScopes.email,
      AppleIDAuthorizationScopes.fullName,
    ]);
    if (credential.identityToken != null) {
      LoginDao.appleLogin(credential.identityToken!, () {
        _initDatas();
        LogPvManager.stat(page: Constants.pageLoginSuccess);
      });
    }
  }

  void _fastInLogin() {
    LogPvManager.stat(page: Constants.pageQuickLogin);
    LoginDao.fastLogin(() {
      _initDatas();
      LogPvManager.stat(page: Constants.pageLoginSuccess);
    }, (error) {
      ToastUtils.showCenter(error);
    });
  }

  void _login(LoginType type) {
    type == LoginType.fastLogin ? _fastInLogin() : _appleLogin();
  }

  _initDatas() async {
    var datalist =
        await DatabaseService.instance.getAuthorList() as List<Author>;
    setState(() {
      loading = true;
    });
    if (datalist.isEmpty) {
      List<Author> authorList = await BroadCasterDao.broadcasterWall();
      DatabaseService.instance.addAuthorList(authorList);
      List<Media> medialist = await MediaDao.getvideolist(Constants.medialist);

      List<int> useridlist =
          authorList.map((e) => int.parse(e.userId!)).toList();
      shuffleList(useridlist);
      useridlist = useridlist.sublist(0, 12);
      var a = 0;
      for (int j = 0; j < Constants.count.length; j++) {
        for (int i = 0; i < Constants.count[j]; i++) {
          Creation creation = Constants.local_creation_list[a];
          creation.userId = useridlist[j];
          a++;
          DatabaseService.instance.addCreation(creation);
        }
      }

      for (int x = 0; x < medialist.length; x++) {
        Media media = medialist[x];
        media.userId = useridlist[x];
        media.title = Constants.local_creation_list[x].title;
        media.describe = Constants.mediaDescribe[x];
        media.videoId = Random().nextInt(100000) + 100000;
        DatabaseService.instance.addMedia(media);
      }

      var user = AppManager.getUserInfo();
      DatabaseService.instance.addAuthor(Author(
          userId: user.userId,
          avatar: user.avatarUrl,
          nickname: user.nickname,
          gender: user.gender,
          age: user.age,
          followNum: user.followNum,
          isFriend: false));
    }
    Get.to(() => const TabNavigationPage());
  }
}

enum LoginType { fastLogin, appleLogin }
